from flask import Flask
from celery import Celery


def make_celery(app: Flask):
    celery_app = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'],
                        backend=app.config['CELERY_RESULT_BACKEND'],
                        include=['applications.common.tasks.spider_tasks'])
    celery_app.conf.update(app.config)

    class ContextTask(celery_app.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery_app.Task = ContextTask
    celery_app.set_default()
    app.extensions["celery"] = celery_app
    return celery_app
